package main

import (
    "gotest/tree"
    "fmt"
)

// Walk 步进 tree t 将所有的值从 tree 发送到 channel ch。
func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    if t.Left != nil {
        Walk(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        Walk(t.Right, ch)
    }
}

// Same 检测树 t1 和 t2 是否含有相同的值。
func Same(t1, t2 *tree.Tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {
        Walk(t1, ch1)
        close(ch1)
    }()
    go func() {
        Walk(t2, ch2)
        close(ch2)
    }()

    for {
        i, ok1 := <-ch1
        j, ok2 := <-ch2

        fmt.Println("i =", i, ",j =", j)

        if ok1 == false && ok2 == false {
            return true
        }
        if ok1 == false || ok2 == false {
            return false
        }
        if i != j {
            return false
        }

    }
        
    return true
}

func main() {
    fmt.Println("start")

    var t1,t2 *tree.Tree
    t1 = tree.New(10)
    t2 = tree.New(10)

    ok := Same(t1,t2)

    fmt.Println("result :", ok)
}
